﻿using System.Collections.Generic;

namespace YueRu.Common
{
    public static class ObjectExtend
    {
        public static IDictionary<string, string> ToDictionary<T>(T t)
        {
            if (t == null) return null;

            System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

            if (properties.Length <= 0) return null;

            SortedDictionary<string, string> dic = new SortedDictionary<string, string>();

            foreach (System.Reflection.PropertyInfo item in properties)
            {
                //实体类字段名称
                string name = item.Name;
                //该字段的值
                string value = null == item.GetValue(t, null) ? "" : item.GetValue(t, null).ToString();
                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
                    //在此可转换value的类型
                    if (!dic.ContainsKey(name))
                        dic.Add(name, value);

                }
            }

            return dic;
        }
    }
}
